require('./cate.css');
import{changeGoodNum,delGood} from './ajax';


$(function () {

//添加商品数量
$(document).on('click','.add',function (e) {

    let input = $(this).siblings('input');
    let id = input.data('gid');
    let curNum = parseInt(input.val());
    changeGoodNum(id, curNum + 1, id, (res) => {
        if (res.rel == 1) {
            input.val(res.goodnum);
            input.attr('data-cid',res.cart_id);
        } else {
            $.toast(res.msg);
        }
    });
});

//减少商品数量
$(document).on('click','.subtract',function (e) {
    let input = $(this).siblings('input');
    let id = input.data('gid');
    let cart_id = input.data('cid');
    let curNum = parseInt(input.val());
    if (curNum > 1) {
        changeGoodNum(id, curNum - 1, id, (res) => {
            if (res.rel == 1) {
                input.val(res.goodnum);
            } else {
                $.toast(res.msg);
            }
        });
    }else{
        if(cart_id != ""){
            delGood(cart_id, id, (res) => {
                if (res.rel == 1) {
                    input.val(0);
                    input.attr('data-cid',"");
                } else {
                    $.toast(res.msg);
                }
            });
        }



    }

});



    $('.cate-side').on('click', 'li', function () {
        let url = $(this).data('url');

        $(this).addClass('active').siblings().removeClass('active');
        $.ajax({
            type: "get",
            url: url,
            dataType: "json",
            success: function (res) {

                if (res.rel == 1) {
                    renderCateContent(res.data);
                } else if (res.rel == 2) {
                    renderGoodContent(res.data);
                } else {
                    $.toast(res.msg);
                }
            }
        });
    });

    let urlTopid = getTopidFromStr(window.location.href);
    let activeIndex;
    if (urlTopid) {
        $('.cate-side li').each(function (key, val) {
            let url = $(this).data('url');
            let topid = getTopidFromStr(url);
            if (urlTopid == topid) {
                activeIndex = key;
                return;
            }
        });
    }

    $('.cate-side li').eq(activeIndex ? activeIndex : 0).trigger('click');

});

const renderGoodContent = (data) => {
let addCart = ` <div class="box clearfix">
              <div class="num">
                <a href="javascript:;" class="subtract"></a>
                <input type="number" readonly="" data-gid="{{:gid}}"  data-cid="{{:cart_id}}" value="{{:cart_num}}">
                <a href="javascript:;" class="add"></a>
              </div>
            </div>`;
    let markup = `
<div class="list">
    <div class="sub-title" data-id="{{:scond_cat_id}}"><span class="iconfont icon-line"></span> {{:scond_cat_name}} <span class="iconfont icon-line"></span></div>
    <div class="detail" >
        <div class="row">
            {{for catelist}}
            <div class="col-50">
                <a href=${_goodUrl}?gid={{:gid}}>
                    <div class="img-container">
                        <img src="/upload/{{:goods_thumb}}" alt="">
                    </div>
                    <span class="ellipsis">{{:goods_name}}</span>
                    <span class="ellipsis">{{:true_price}}</span>
                </a>
${_level >=1 ? addCart:''}
                  
            
            </div>
            {{/for}}
        </div>
        {{if catelist.length>=9}}
            <a style="margin:0 auto;" data-page="0"  class="button button-light more">加载更多</a>
        {{/if}}
    </div>
</div>
`;
    let template = jsrender.templates(markup);
    let compiledHtml = template.render(data);
    $('.cate-content').html(compiledHtml);

    $('.detail .more').click(function (e) {
        loadHandler(this);
    });


};

const loadHandler = (self) => {

    let page = $(self).data('page');
    let scond_cat_id = $(self).parents('.list').find('.sub-title').data('id');
    let url = `${_goodListUrl}?page=${page+1}&topid=${scond_cat_id}`;
    $(self).before(loadingTemplate());
    $(self).hide();
    $.ajax({
        type: "get",
        url: url,
        data: "data",
        dataType: "json",
        success: function (res) {
            if (res.rel == 1) {
                if (res.data.catelist.length > 0) {
                    $(self).siblings('.row').append(goodTemplate(res.data));
                    $(self).data('page', page + 1);
                }
                $(self).siblings('.infinite-scroll-preloader').remove();
                if (res.data.catelist.length >= 9) {
                    $(self).show();
                }
            } else {
                $(self).siblings('.infinite-scroll-preloader').remove();
                $.toast(res.msg);
            }
        }
    });
}


const goodTemplate = (data) => {
let addCart = ` <div class="box clearfix">
              <div class="num">
                <a href="javascript:;" class="subtract"></a>
                <input type="number" readonly="" data-gid="{{:gid}}" data-cid="{{:cart_id}}" value="{{:cart_num}}">
                <a href="javascript:;" class="add"></a>
              </div>
            </div>`;

    let markup = `
     {{for catelist}}
            <div class="col-50">
                <a href=${_goodUrl}?cid={{:gid}}>
                    <div class="img-container">
                        <img src="/upload/{{:goods_thumb}}" alt="">
                    </div>
                    <span class="ellipsis">{{:goods_name}}</span>
                    <span class="ellipsis">{{:true_price}}</span>
                </a>
${_level >=1 ? addCart:''}


            </div>
    {{/for}}
    `;

    let template = jsrender.templates(markup);
    let compiledHtml = template.render(data);
    return compiledHtml;
};


const loadingTemplate = () => {
    return `
       <div class="infinite-scroll-preloader">
              <div class="preloader"></div>
          </div>`;
}

const renderCateContent = (data) => {
    let markup = `
<div class="list">
    <div class="sub-title"><span class="iconfont icon-line"></span> {{:scond_cat_name}} <span class="iconfont icon-line"></span></div>
    <div class="detail">
        <div class="row">
            {{for catelist}}
            <div class="col-33">
                <a href=${_cateUrl}?cid={{:cat_id}}>
                    <div class="img-container">
                        <img src="{{:cateimg}}" alt="">
                    </div>
                    <span class="ellipsis">{{:cat_name}}</span>
                </a>

            </div>
            {{/for}}
        </div>
    </div>
</div>
`;
    let template = jsrender.templates(markup);
    let compiledHtml = template.render(data);
    $('.cate-content').html(compiledHtml);
};



const getTopidFromStr = (str) => {

    let regex = /topid\/\d/;
    let res = str.match(regex);
    if (!res) {
        return null;
    }
    let topid = res[0].split('/')[1];
    return topid;

};

